import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';
import router from 'umi/router';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Card,
  Row,
  Col,
  Input,
  Select,
  Button,
  Modal,
  message,
} from 'antd';
import { createFromIconfontCN, SearchOutlined } from '@ant-design/icons';

import '@ant-design/compatible/assets/index.css';
import { DetailInfoItem } from './data';
import SaveGardenList from './components/SaveGardenList';

const { Option } = Select;
const { TextArea } = Input;
const { Item } = Form;
const MyIcon = createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1430304_y2xsdrlvrh.jss',
});

interface PostManageAddProps extends FormComponentProps {
  dispatch: Dispatch;
  detailInfo: DetailInfoItem;
  gardenInfo: any;
  postTariffList: any[];
  location: { query: any };
}

interface PostManageAddState {
  saveVisible: boolean;
  gardenInfo: {
    id: number | string;
    name: string;
  };
  addAdmin: {
    id: number;
    number: number;
    adminName: string;
    adminPhone: string;
    type: boolean }[];
  is_detail: boolean;
  delVisible: boolean;
  delId: number;
  delIndex: number;
}

@connect(({
  postManagementAdd: { detailInfo, gardenInfo, postTariffList },
}: any) => ({
  detailInfo,
  gardenInfo,
  postTariffList,
}))

class PostManagementAddElem extends Component<PostManageAddProps, PostManageAddState> {
  state: PostManageAddState = {
    saveVisible: false,
    gardenInfo: { id: '', name: '' },
    addAdmin: [
      {
        id: 1,
        number: 0,
        adminName: '',
        adminPhone: '',
        type: false,
      },
    ],
    is_detail: false, // 是否存在回显信息
    delVisible: false, // 显示删除确认框
    delId: 0,
    delIndex: 0,
  };

  static getDerivedStateFromProps(nextProps: PostManageAddProps, preState: PostManageAddState) {
    const {
      detailInfo: {
        gardenId, gardenName, id, managerStr,
      },
    } = nextProps;
    const { is_detail } = preState;
    if (id && !is_detail) {
      const gardenInfo = {
        // 设置小区信息
        id: gardenId || 0,
        name: gardenName || '',
      };

      const addAdmin = managerStr
        ? managerStr.split(',').map((item: string) => ({
          // 设置管理员信息
          id: Number(item.split('-')[0]),
          number: Number(item.split('-')[0]),
          adminName: item.split('-')[1],
          adminPhone: item.split('-')[2],
          type: true,
        }))
        : [];
      return {
        gardenInfo,
        addAdmin,
        is_detail: true,
      };
    }
    return null;
  }

  componentDidMount() {
    const {
      location: { query: { id } },
    } = this.props;
    if (id) this.fetchDetailInfo(id);
    this.fetchAction('common/fetchGardenType');
    this.fetchAction('fetchPosthouseTariff');
  }

  componentDidUpdate(props: any) {
    const {
      location: { query: { id } },
    } = this.props;
    if (id && id !== props.location.query.id) {
      this.fetchDetailInfo(id);
    }
  }

  componentWillUnmount() {
    this.fetchAction('clear');
  }

  fetchDetailInfo = (id: number) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'postManagementAdd/fetch',
      payload: { id },
    });
  };

  handleSearchGarden = (saveVisible: boolean, row?: any) => {
    const { gardenInfo } = this.state;
    const { form: { setFieldsValue } } = this.props;
    setFieldsValue({ gardenId: row ? row.name : gardenInfo.name });
    this.setState({
      saveVisible,
      gardenInfo: row ? { id: row.id, name: row.name } : gardenInfo,
    });

    if (saveVisible) {
      const params = {
        pareaCode: '',
        name: '',
        type: '',
        propertyId: '',
        pageIndex: 1,
        pageSize: 20,
      };
      this.fetchAction('fetchGarden', params);
    }
  };

  handleChangeInput = ({ target: { value } }: any, typeName: string, index: number) => {
    const { addAdmin } = this.state;
    const new_addAdmin = addAdmin.map(item => item);
    new_addAdmin[index][typeName] = value;
    this.setState({ addAdmin: new_addAdmin });
  };

  handleChangeAddAdmin = (addOrDel: number, index: number = -1, type?: boolean) => {
    const { form: { resetFields } } = this.props;
    resetFields(['adminName', 'adminPhone']);

    const { addAdmin } = this.state;
    const params: any = addAdmin.map(item => ({ ...item }));
    if (addOrDel === 1) {
      const id = addAdmin.length > 0 ? addAdmin[addAdmin.length - 1].id + 1 : 1;
      params.push({
        id,
        number: 0,
        adminName: '',
        adminPhone: '',
        type: false,
      });
    }

    if (addOrDel === 2 && index >= 0) {
      if (type) {
        this.handleChangeDelAdminModal(true, index, params[index].id);
      } else {
        params.splice(index, 1);
      }
    }
    this.setState({ addAdmin: params });
  };

  handleChangeDelAdminModal = (delVisible: boolean, delIndex: number = 0, delId: number = 0) => {
    this.setState({ delVisible, delId, delIndex });
  };

  handleDeleteAdmin = () => {
    const { location: { query } } = this.props;
    const { delId, delIndex } = this.state;
    const params = { state: query ? query.id : '', id: delId };
    this.fetchAction('delete', params);

    this.handleChangeAddAdmin(2, delIndex);
    this.handleChangeDelAdminModal(false);
  };

  handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFieldsAndScroll } } = this.props;
    validateFieldsAndScroll((errors, values) => {
      if (errors) return;

      const { longitude, latitude } = values;
      if (longitude.length > 16 || Number(longitude) < -180 || Number(longitude) > 180) {
        message.error('经度输入不正确');
        return;
      }
      if (latitude.length > 16 || Number(latitude) < -90 || Number(latitude) > 90) {
        message.error('纬度输入不正确');
        return;
      }

      const { adminId, adminName, adminPhone } = values;
      const adminInfo = adminId && adminId.length > 0
        ? adminId.map((item: number, index: number) => [
          `${item}-${adminName[index]}-${adminPhone[index]}`,
        ])
        : [];
      const { gardenInfo: { id: gardenId } } = this.state;
      const params = {
        ...values,
        gardenId,
        managerStr: adminInfo.join(','),
      };
      delete params.adminId;
      delete params.adminName;
      delete params.adminPhone;

      const { location: { query } } = this.props;
      if (query) params.id = query.id;
      this.fetchAction('saveOrUpdate', params);
    });
  };

  fetchAction = (typeName: string, payload: any = {}) => {
    const { dispatch } = this.props;
    const type = typeName.indexOf('common') >= 0
      ? typeName : `postManagementAdd/${typeName}`;
    dispatch({ type, payload });
  };

  renderAdminInfo = () => {
    const { addAdmin } = this.state;
    const { form: { getFieldDecorator } } = this.props;

    return (
      <Row gutter={48}>
        {addAdmin.map((item: any, index: number) => (
          <Col key={item.id} md={12} sm={24} className="marginB20">
            <Row className="dottedBox">
              <Col
                span={3}
                className="linH32"
                style={{ minWidth: 56 }}
              >
                <span
                  className="operLink"
                  onClick={() => this.handleChangeAddAdmin(2, index, item.type)}
                  style={{ color: '#ff4d4f' }}
                >
                  <MyIcon type="iconjianhao" style={{ margin: '4px 4px 0 0' }} />
                  删除
                </span>
              </Col>
              <Col span={18}>
                {getFieldDecorator(`adminId[${index}]`, { initialValue: item.number })(<div />)}
                <Item label="管理员" colon={false} style={{ marginBottom: 12 }}>
                  {getFieldDecorator(`adminName[${index}]`, {
                    initialValue: item.adminName,
                    rules: [{ required: true, message: '请输入管理员姓名' }],
                  })(
                    <Input
                      allowClear
                      placeholder="请输入管理员姓名"
                      disabled={item.type}
                      onChange={e => this.handleChangeInput(e, 'adminName', index)}
                    />,
                  )}
                </Item>
                <Item label="　手机" colon={false}>
                  {getFieldDecorator(`adminPhone[${index}]`, {
                    initialValue: item.adminPhone,
                    rules: [{ required: true, message: '请输入管理员手机' }],
                  })(
                    <Input
                      allowClear
                      type="number"
                      placeholder="请输入管理员手机"
                      disabled={item.type}
                      onChange={e => this.handleChangeInput(e, 'adminPhone', index)}
                    />,
                  )}
                </Item>
              </Col>
            </Row>
          </Col>
        ))}
      </Row>
    );
  };

  render() {
    const { saveVisible, gardenInfo, delVisible } = this.state;
    const {
      form: { getFieldDecorator },
      detailInfo,
      postTariffList,
    } = this.props;

    return (
      <Fragment>
        <PageHeader />

        <Form hideRequiredMark className="tableListForm" onSubmit={this.handleSubmit}>
          <Card title="编辑驿站信息" bordered={false}>
            {detailInfo.id && (
              <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
                <Col md={8} sm={24}>
                  <Item label="　　驿站编号">{detailInfo.code}</Item>
                </Col>
                <Col md={8} sm={24}>
                  <Item label="　　　加盟商">{detailInfo.contactName || '--'}</Item>
                </Col>
                <Col md={8} sm={24}>
                  <Item label="　　联系电话">{detailInfo.phone || '--'}</Item>
                </Col>
              </Row>
            )}
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={8} sm={24}>
                <Item label="　　驿站名称" colon={false}>
                  {getFieldDecorator('name', {
                    initialValue: detailInfo.name,
                    rules: [{ required: true, message: '请输入驿站名称' }],
                  })(<Input allowClear placeholder="请输入" />)}
                </Item>
              </Col>
              <Col md={8} sm={24}>
                <Item label="　　　　小区" colon={false}>
                  {getFieldDecorator('gardenId', {
                    initialValue: gardenInfo.name,
                    rules: [{ required: true, message: '请选择小区' }],
                  })(
                    <Input
                      allowClear
                      placeholder="请选择"
                      readOnly
                      suffix={<SearchOutlined />}
                      onClick={() => this.handleSearchGarden(true)}
                    />,
                  )}
                </Item>
              </Col>
              <Col md={8} sm={24}>
                <Item label="　　　　状态" colon={false}>
                  {getFieldDecorator('isValid', {
                    initialValue: detailInfo.id ? detailInfo.isValid : 1,
                    rules: [{ required: true, message: '请选择状态' }],
                  })(
                    <Select placeholder="请选择">
                      <Option value={1}>启用</Option>
                      <Option value={0}>禁用</Option>
                    </Select>,
                  )}
                </Item>
              </Col>
            </Row>
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={8} sm={24}>
                <Item label="　　服务时间" colon={false}>
                  {getFieldDecorator('businessHour', {
                    initialValue: detailInfo.businessHour,
                    rules: [{ required: false, message: '请输入服务时间' }],
                  })(<Input allowClear placeholder="请输入" />)}
                </Item>
              </Col>
              <Col md={8} sm={24}>
                <Item label="　　驿站套餐" colon={false}>
                  {getFieldDecorator('tariffId', {
                    initialValue: detailInfo.tariffId,
                    rules: [{ required: true, message: '请选择驿站套餐' }],
                  })(
                    <Select placeholder="请选择">
                      {postTariffList.map((item: any) => (
                        <Option value={item.id} key={item.id}>
                          {item.name}
                        </Option>
                      ))}
                    </Select>,
                  )}
                </Item>
              </Col>
              <Col md={8} sm={24}>
                <Item label="　　投递上限" colon={false}>
                  {getFieldDecorator('capacity', {
                    initialValue: detailInfo.capacity,
                    rules: [{ required: true, message: '请输入投递上线' }],
                  })(<Input allowClear placeholder="请输入" />)}
                </Item>
              </Col>
            </Row>
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={8} sm={24}>
                <Item label="滞留时间阈值" colon={false}>
                  {getFieldDecorator('detentionDay', {
                    initialValue: detailInfo.detentionDay,
                    rules: [{ required: true, message: '请输入滞留时间阈值' }],
                  })(<Input
                    allowClear
                    type="number"
                    placeholder="请输入"
                    suffix="天"
                  />)}
                </Item>
              </Col>
              <Col md={8} sm={24}>
                <Item label="　　　　经度" colon={false}>
                  {getFieldDecorator('longitude', {
                    initialValue: detailInfo.longitude,
                    rules: [{ required: true, message: '请输入经度' }],
                  })(
                    <Input
                      allowClear
                      type="number"
                      step={0.00000000000001}
                      placeholder="请输入"
                    />,
                  )}
                </Item>
              </Col>
              <Col md={8} sm={24}>
                <Item label="　　　　纬度" colon={false}>
                  {getFieldDecorator('latitude', {
                    initialValue: detailInfo.latitude,
                    rules: [{ required: true, message: '请输入纬度' }],
                  })(
                    <Input
                      allowClear
                      type="number"
                      step={0.00000000000001}
                      placeholder="请输入"
                    />,
                  )}
                </Item>
              </Col>
            </Row>
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={8} sm={24}>
                <Item label="　　驿站地址" colon={false}>
                  {getFieldDecorator('addr', {
                    initialValue: detailInfo.addr,
                    rules: [{ required: true, message: '请输入驿站地址' }],
                  })(
                    <TextArea placeholder="请输入详细地址" />,
                  )}
                </Item>
              </Col>
            </Row>
          </Card>

          <Card
            bordered={false}
            title="管理员信息"
            extra={
              <span
                className="operLink"
                onClick={() => this.handleChangeAddAdmin(1)}
              >
                增加
              </span>
            }
          >
            {this.renderAdminInfo()}
          </Card>

          <Card bordered={false}>
            <Button
              type="primary"
              htmlType="submit"
            >
              保存
            </Button>
            <Button
              ghost
              type="primary"
              className="marginL16"
              onClick={() => router.goBack()}
            >
              取消
            </Button>
          </Card>

        </Form>
        <SaveGardenList
          saveVisible={saveVisible}
          searchGarden={this.handleSearchGarden.bind(this)}
        />
        <Modal
          title="删除确认"
          visible={delVisible}
          onOk={this.handleDeleteAdmin}
          onCancel={() => this.handleChangeDelAdminModal(false)}
        >
          <p>确定删除当前管理员？</p>
        </Modal>
      </Fragment>
    );
  }
}

export default Form.create<PostManageAddProps>()(PostManagementAddElem);
